/**
 * 
 */
package com.shine.icis.dao.imp;

import java.sql.CallableStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;

import com.shine.cotrun.sql.QueryParameters;
import com.shine.cotrun.sql.hibernate.CommQuery;
import com.shine.cotrun.web.comm.ListPage;
import com.shine.icis.dao.IStockCheckDAO;
import com.shine.icis.dto.ReturnMsg;
import com.shine.icis.hbean.StockChk;
import com.shine.icis.hbean.StockChkSurv;
import com.shine.icis.hbean.StockCheckProcStatus;

/**
 * @author zuohp
 * 
 */
public class StockCheckDAO extends BaseHibernateDAO implements IStockCheckDAO {

	/**
	 * 取得处理状态
	 * 
	 * @author zuohp 2012-08-30
	 * @param procID
	 *            ,queryDate
	 **/
	public StockCheckProcStatus findProcStatus(int procID, int queryDate) {
		Query query;
		query = this
				.getSession()
				.createQuery(
						"from StockCheckProcStatus as dc where dc.etlProcID=:etlProcID and dc.busiDate=:busiDate ");

		query.setInteger("etlProcID", procID);
		query.setInteger("busiDate", queryDate);
		query.setMaxResults(1);
		return (StockCheckProcStatus) query.uniqueResult();
	}

	public int findPreviousBusiDate(int date) {
		Query query = getSession().getNamedQuery(
				"StockCheckDAO.findPreviousBusiDate");
		query.setInteger(0, date);
		query.setMaxResults(1);
		Integer d = (Integer) query.uniqueResult();
		return d == null ? 0 : d;
	}
	public int findPreviousDate(int date) {
		Query query = getSession().getNamedQuery(
				"StockCheckDAO.findPreviousDate");
		query.setInteger(0, date);
		query.setMaxResults(1);
		Integer d = (Integer) query.uniqueResult();
		return d == null ? 0 : d;
	}
	@SuppressWarnings("deprecation")
	public ReturnMsg callCollectProc(String proSql, int busiDate,
			String exchangeType, String srcFlag) {
		try {
			CallableStatement proc = getSession().connection().prepareCall(
					proSql);
			proc.setInt(1, busiDate);
			proc.setString(2, exchangeTypeFlagGet(exchangeType));
			proc.setString(3, srcFlagGet(srcFlag));
			proc.registerOutParameter(4, Types.VARCHAR);
			proc.registerOutParameter(5, Types.INTEGER);

			proc.execute();
			String msg = proc.getString(4);
			int code = proc.getInt(5);
			proc.close();
			return new ReturnMsg(code, msg);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new HibernateException(e);
		}

	}

	private String exchangeTypeFlagGet(String exchangeType) {
		boolean haFlag = false;
		boolean hbFlag = false;
		boolean saFlag = false;
		boolean sbFlag = false;
		boolean staFlag = false;
		boolean stbFlag = false;
		boolean ofFlag = false;
		StringBuffer sb = new StringBuffer();
		if (exchangeType == null || exchangeType.trim().equals("")) {
			return sb.append("1111111").toString();
		} else {
			String[] parNameArray = exchangeType.split(",");
			for (int i = 0; i < parNameArray.length; i++) {
				if (parNameArray[i].equals("1")) {
					haFlag = true;
				} else if (parNameArray[i].equals("D")) {
					hbFlag = true;
				} else if (parNameArray[i].equals("2")) {
					saFlag = true;
				} else if (parNameArray[i].equals("H")) {
					sbFlag = true;
				} else if (parNameArray[i].equals("9")) {
					staFlag = true;
				} else if (parNameArray[i].equals("A")) {
					stbFlag = true;
				} else if (parNameArray[i].equals("OF")) {
					ofFlag = true;
				}
			}
			return sb.append((haFlag ? "1" : "0")).append(hbFlag ? "1" : "0")
					.append(saFlag ? "1" : "0").append(sbFlag ? "1" : "0")
					.append(staFlag ? "1" : "0").append(stbFlag ? "1" : "0")
					.append(ofFlag ? "1" : "0").toString();
		}
	}

	private String srcFlagGet(String srcFlag) {
		boolean seFlag = false;
		boolean hsFlag = false;
		StringBuffer sb = new StringBuffer();
		if (srcFlag == null || srcFlag.trim().equals("")) {
			return sb.append("11").toString();
		} else {
			String[] parNameArray = srcFlag.split(",");
			for (int i = 0; i < parNameArray.length; i++) {
				if (parNameArray[i].equals("0")) {
					seFlag = true;
				}
				if (parNameArray[i].equals("1")) {
					hsFlag = true;
				}
			}
			return sb.append((seFlag ? "1" : "0")).append((hsFlag ? "1" : "0"))
					.toString();
		}
	}

	@SuppressWarnings("deprecation")
	public ReturnMsg callCheckProc(String proSql, int busiDate,String exchangeType) {
		try {
			CallableStatement proc = getSession().connection().prepareCall(
					proSql);
			proc.setInt(1, busiDate);
			proc.setString(2, exchangeTypeFlagGet(exchangeType));
			proc.registerOutParameter(3, Types.VARCHAR);
			proc.registerOutParameter(4, Types.INTEGER);

			proc.execute();
			String msg = proc.getString(3);
			int code = proc.getInt(4);
			proc.close();
			return new ReturnMsg(code, msg);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new HibernateException(e);
		}
	}

	private void queryHqlSet(String queryColName, QueryParameters qp,
			StringBuffer sbQueryString) {
		int parLen = (Integer) qp.getParameter(queryColName + "Cnt");
		if (parLen > 1) {
			for (int i = 0; i < parLen; i++) {
				if (i == 0) {
					sbQueryString.append(" and ( ai." + queryColName + " = :"
							+ queryColName + i);
				} else if (i == parLen - 1) {
					sbQueryString.append(" or ai." + queryColName + " = :"
							+ queryColName + i + ") ");
				} else {
					sbQueryString.append(" or ai." + queryColName + " = :"
							+ queryColName + i);
				}
			}
		} else {
			sbQueryString.append(" and ai." + queryColName + " in (:"
					+ queryColName + ")");
		}
	}

	@Override
	public ListPage<StockChk> findListPage(QueryParameters qp) {
		if (qp == null) {
			throw new IllegalArgumentException();
		}

		try {
			StringBuffer sbQueryString = new StringBuffer();
			sbQueryString.append("select ai from StockChk as ai where 1=1");
			if (qp.getParameter("queryDate") != null) {
				sbQueryString.append(" and ai.busiDate = :queryDate");
			}
			if (qp.getParameter("diffType") != null) {
				queryHqlSet("diffType", qp, sbQueryString);
			}
			if (qp.getParameter("compType") != null) {
				queryHqlSet("compType", qp, sbQueryString);
			}
			if (qp.getParameter("exchangeType") != null) {
				queryHqlSet("exchangeType", qp, sbQueryString);
			}
			if (qp.getParameter("stockAccount") != null) {
				sbQueryString.append(" and ai.stockAccount=:stockAccount");
			}
			if (qp.getParameter("stockCode") != null) {
				sbQueryString.append(" and ai.stockCode=:stockCode");
			}
			return new CommQuery<StockChk>().queryListPage(qp,
					qp.appendOrders(sbQueryString, "ai"), getSession());
		} catch (RuntimeException re) {
			re.printStackTrace();
			return new ListPage<StockChk>();
		}
	}

	@Override
	public ListPage<StockChkSurv> findSurvListPage(QueryParameters qp) {
		if (qp == null) {
			throw new IllegalArgumentException();
		}
		try {
			StringBuffer sbQueryString = new StringBuffer();
			sbQueryString.append("select ai from StockChkSurv as ai where 1=1");

			if (qp.getParameter("diffType") != null) {
				// sbQueryString.append(" and ai.diffType=:diffType");
				queryHqlSet("diffType", qp, sbQueryString);
			}
			if (qp.getParameter("exchangeType") != null) {
				// sbQueryString.append(" and ai.exchangeType=:exchangeType");
				queryHqlSet("exchangeType", qp, sbQueryString);
			}
			if (qp.getParameter("stockAccount") != null) {
				sbQueryString.append(" and ai.stockAccount=:stockAccount");
			} else {
				if (qp.getParameter("queryDate") != null) {
					sbQueryString
							.append(" and ai.validDate <= :queryDate and ai.invalidDate >= :queryDate");
				}
			}

			if (qp.getParameter("stockCode") != null) {
				sbQueryString.append(" and ai.stockCode=:stockCode");
			}
			return new CommQuery<StockChkSurv>().queryListPage(qp,
					qp.appendOrders(sbQueryString, "ai"), getSession());
		} catch (RuntimeException re) {
			re.printStackTrace();
			return new ListPage<StockChkSurv>();
		}
	}

	@SuppressWarnings("deprecation")
	public ReturnMsg callBackupProc(String proSql, int busiDate) {
		try {
			CallableStatement proc = getSession().connection().prepareCall(
					proSql);
			proc.setInt(1, busiDate);
			proc.registerOutParameter(2, Types.VARCHAR);
			proc.registerOutParameter(3, Types.INTEGER);

			proc.execute();
			String msg = proc.getString(2);
			int code = proc.getInt(3);
			proc.close();
			return new ReturnMsg(code, msg);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new HibernateException(e);
		}
	}

	@Override
	public StockChkSurv findById(long id) {
		StockChkSurv sl = (StockChkSurv) getSession().get(StockChkSurv.class,
				id);
		return sl;
	}

	@Override
	public void modifyStockSurv(long id, int queryDate) {
		Query query = getSession().getNamedQuery("StockCheckDAO.update");
		query.setLong("id", id);
		query.setInteger("queryDate", queryDate);
		query.executeUpdate();
	}

	@Override
	public void save(StockChkSurv surv) {
		Query query = getSession().getNamedQuery("StockCheckDAO.save");
		query.setInteger("branchNo", surv.getBranchNo());
		query.setString("exchangeType", surv.getExchangeType());
		query.setString("taCode", surv.getTaCode());
		query.setString("stockAccount", surv.getStockAccount());
		query.setString("stockCode", surv.getStockCode());
		query.setInteger("fundAccount", surv.getFundAccount());
		//query.setString("clientId", surv.getClientId());
		query.setDouble("dzAmount", surv.getDzAmount());
		query.setDouble("hsAmount", surv.getHsAmount());
		query.setString("diffType", surv.getDiffType());
		query.setString("note", surv.getNote());
		query.setInteger("validDate", surv.getValidDate());
		query.executeUpdate();
	}

	@Override
	public void modifyStockSurvNote(StockChkSurv surv, StockChkSurv oldSurv) {
		Query query = getSession().getNamedQuery("StockCheckDAO.updateNote");
		query.setLong("id", oldSurv.getId());
		query.setString("note", surv.getNote());
		query.executeUpdate();
	}

	@Override
	public StockChk findStockChkById(long id) {
		StockChk stockChk = (StockChk) getSession().get(StockChk.class, id);
		return stockChk;
	}

	@Override
	public void modifyNote(long id, String note) {
		Query query = this.getSession().getNamedQuery(
				"StockCheckDAO.updateStockChkNote");
		query.setLong("id", id);
		query.setString("note", note);
		query.executeUpdate();
	}
}
